package com.example.smartcity.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;

import com.example.smartcity.R;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.RecyclerView;


import com.google.gson.Gson;
import com.example.smartcity.search.FlowLayoutManager;
import com.example.smartcity.search.HotSearchFlowLayout;
import com.example.smartcity.search.SearchDBHelper;
import com.example.smartcity.search.SearchResponse;
import com.example.smartcity.search.Searchdata;
import com.example.smartcity.search.SearchHistoryAdapter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class SearchActivity extends AppCompatActivity {
    ImageButton searchbottonback;
    EditText searchedittext;
    TextView startserch;
    RecyclerView searchrecordflowlayout;
    ImageButton deletesearchrecord;
    public SQLiteDatabase db;
    private SearchDBHelper dbHelper;
    HotSearchFlowLayout hotsearchflowlayout;
    SearchHistoryAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        searchbottonback = findViewById(R.id.searchbottonback);
        searchedittext = findViewById(R.id.searchedittext);
        startserch = findViewById(R.id.startsearch);
        searchrecordflowlayout = findViewById(R.id.searchrecord_flowlayout);
        deletesearchrecord = findViewById(R.id.deletesearchrecord);
        hotsearchflowlayout = findViewById(R.id.hotsearch_flowlayout);
        initDataBaseByHelper();
        List<String> SearchRecord = getSearchRecord();
        //showSearchRecordOnListView(SearchRecord);
        adapter = new SearchHistoryAdapter(SearchRecord,new SearchHistoryAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(String item) {
                Intent intent = new Intent(SearchActivity.this, NewsActivity.class);
                intent.putExtra("keyword", item);
                Log.i("item", item);
                startActivity(intent);
            }
        });
        if (searchrecordflowlayout != null) {
            // 设置适配器
            searchrecordflowlayout.setAdapter(adapter);
            FlowLayoutManager flowLayoutManager = new FlowLayoutManager(this,false);
            searchrecordflowlayout.setLayoutManager(flowLayoutManager);
            //MyAdapter adapter = new MyAdapter();
            //recyclerView.setAdapter(adapter);
        } else {
            // 处理 RecyclerView 为 null 的情况
        }
// ... 可以根据需要设置其他FlexboxLayout属性

        hotSearchThread();


        searchbottonback.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        startserch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String keyword = String.valueOf(searchedittext.getText());
                saveSearchRecord(keyword);
                // 更新数据源和界面
                refreshSearchAdapter();
                // 启动搜索结果Activity
                Intent intent = new Intent(SearchActivity.this, NewsActivity.class);
                intent.putExtra("keyword", keyword);
                startActivity(intent);
            }
        });
        deletesearchrecord.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dbHelper.onDelete(db);
                // 更新数据源和界面
                refreshSearchAdapter();
            }
        });
    }
    //将用户的搜索记录存储起来
    private void saveSearchRecord(String keyword) {
        // 创建一个ContentValues对象用于存储插入的数据
        ContentValues values = new ContentValues();
        values.put("title", keyword); // 替换"keyword_column_name"为你的数据库表中的关键字列名
        // 执行插入操作
        long newRowId = db.insert("searchrecord", null, values); // 替换"your_table_name"为你的数据库表名
        if (newRowId != -1) {
            // 插入成功
            Log.d("TAG", "Insertion successful");
        } else {
            // 插入失败
            Log.d("TAG", "Insertion failed");
        }
    }
    //从本地数据库里面获取搜索记录方法
    private List<String> getSearchRecord() {
        List<String> list = new ArrayList<String>();
        List<String> result = new ArrayList<String>();
        Cursor cursor = db.query(true, "searchrecord", new String[] {"title"}, null, null, null, null, null, null);
        if (cursor.moveToFirst()) {
            do {
                @SuppressLint("Range") String title=cursor.getString(cursor.getColumnIndex("title"));
                list.add(title);
                Log.d("TAG", title);
            } while (cursor.moveToNext());
        }
        result = list.subList(0,list.size());
        return result;
    }
    //实现热搜的方法
    private void hotSearchThread(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                List<String> hotsearchresult;
                //创建okhttp对象
                OkHttpClient client = new OkHttpClient();
                //创建request对象
                //创建用于构造request对象的builder对象
                Request.Builder builder = new Request.Builder().get().url("http://10.7.89.170:5503/kungfucook/v1/uploadDownload/downloadRecommend");//todo
                //用builder来构建request对象
                Request request = builder.build();
                //获取call对象
                Call call = client.newCall(request);
                //提交请求，执行网络操作，获取服务器返回的响应对象
                String shicai = null;
                try {
                    Response response = call.execute();
                    shicai = response.body().string();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                //Log.i("msg",shicai);
                Gson gson = new Gson();
                SearchResponse response = gson.fromJson(shicai, SearchResponse.class);
                //空判断
                hotsearchresult = new ArrayList<String>();
                if(response==null){
                    hotsearchresult.add("太冷了，没有热搜");
                    hotsearchresult.add("你连网了吗？");
//                    List<String> nullhotsearch  = new ArrayList<String>();
//                    nullhotsearch.add("空的...你没联网吗？");
                }else{
                    for (Searchdata res:response.getData()){
                        hotsearchresult.add(res.getDishName());
                    }
                }
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        showHotSearchOnFlowLoyOut(hotsearchresult);
                    }
                });
            }
        }).start();
    }
    private void showHotSearchOnFlowLoyOut(List<String> dataList){
        Log.i("msg", String.valueOf(dataList.size()));
        for (int i = 0; i < dataList.size(); i++) {
            RelativeLayout.LayoutParams hotsearchlayout = new RelativeLayout.LayoutParams(
                    RelativeLayout.LayoutParams.WRAP_CONTENT,
                    RelativeLayout.LayoutParams.WRAP_CONTENT);
            hotsearchlayout.setMargins(10, 20, 10, 20);
            TextView textView = new TextView(this);
            textView.setText(dataList.get(i));
            textView.setPadding(10, 10, 10, 10);
            //textView.setBackgroundResource(R.drawable.searchrecordview);
            textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20);
            textView.setLayoutParams(hotsearchlayout);
            textView.setClickable(true);
            textView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    String keyword = textView.getText().toString();
                    Intent i = new Intent(SearchActivity.this, NewsActivity.class);
                    i.putExtra("keyword",keyword);
                    saveSearchRecord(keyword);
                    refreshSearchAdapter();
                    startActivity(i);
                }
            });
            hotsearchflowlayout.addView(textView);
        }
    }
    //本地数据库初始化方法
    private void initDataBaseByHelper(){
        String dbFile = getFilesDir().getAbsolutePath() + "/search.db";
        try {
            db=SQLiteDatabase.openDatabase(dbFile,null,SQLiteDatabase.OPEN_READWRITE);
            Log.i("msg","数据库表打开成功");
        }catch(Exception e){
            db = SQLiteDatabase.openOrCreateDatabase(dbFile, null);
            db.execSQL("CREATE TABLE searchrecord (id INTEGER PRIMARY KEY AUTOINCREMENT, title VARCHAR(100)) ;");
            Log.i("msg","数据库表创建成功");
        }
        dbHelper = new SearchDBHelper(this,"search.db",null,1);

        String dbname = dbHelper.getDatabaseName();
        Log.i("mag",dbname);
    }
    private void hotSearch(){

    }
    private void refreshSearchAdapter() {
        List<String> updatedSearchRecord = getSearchRecord();
        adapter.updateData(updatedSearchRecord); // 假设你的适配器有一个方法来更新数据
        adapter.notifyDataSetChanged();
    }



}